package com.flute.icrawler.app.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class XStreamUtil {

	public static void buildXMLFile(Object object, String filePath) {
		OutputStream outputStream = null;
		try {
			outputStream = new FileOutputStream(filePath);
			OutputStreamWriter writer = new OutputStreamWriter(outputStream,
					Charset.forName("gb2312"));
			writer.write("<?xml version=\"1.0\" encoding=\"GB2312\"?>\r\n");

			XStream xstream = new XStream(new DomDriver());
			xstream.toXML(object, writer);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (outputStream != null) {
					outputStream.close();
				}
				outputStream = null;

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	/**
	 * 加载配置文件
	 * 
	 * @param filePath
	 *            配置文件的绝对路径
	 */
	public static Object newObject(String filePath) {
		try {

			XStream xstream = new XStream(new DomDriver());
			return xstream.fromXML(new FileInputStream(filePath));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}

	}
}
